package admin.data;

import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.SiteConfigModel;

import systems.ConfigSystem;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;

public class SiteConfigData {
	private Objectify ofy;
	
	private Cache cache = null;
	
	public SiteConfigData() {
		try {
			ObjectifyService.register(SiteConfigModel.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public SiteConfigModel getConfig(long id) {
		SiteConfigModel config = new SiteConfigModel();
		if (cache != null && cache.containsKey(id)) {
			config = (SiteConfigModel) cache.get(id);
		} else {
			try {
				config = ofy.get(new Key<SiteConfigModel>(SiteConfigModel.class, id));
				cache.put(id, config);
			} catch (Exception e) {
				config = null;
			}
		}
		return config;
	}
	
	public void insert(SiteConfigModel config) {
		ConfigSystem.setConfigs(config);
		if (cache != null) {
			cache.put(config.getId(), config);
		}
		ofy.put(config);
	}
	
	public void delete(SiteConfigModel config) {
		if (cache != null && cache.containsKey(config.getId())) {
			cache.remove(config.getId());
		}
		ofy.delete(config);
	}
}
